const express = require('express')
const path = require('path')
const cors = require('cors')
const app = express()
const joi = require('joi')

//导入服务器基本配置
const serverConfig = require('./config/server.config.js')
//导入Response回复类
const Response = require('./config/response.config.js')

//导入路由
const userRouter = require('./router/user.js')

//跨域,前端和后端存在一方完成跨域配置就可以互相访问
app.use(cors())

//配置静态资源路径
app.use(express.static(path.join(__dirname, 'public')));  

//使用express的子中间,将req的body中json字符串识别,和urlencoded识别
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.use((req, res, next) => {
	// res.cc = (err, status = 1, ...other) => {
	// 	res.send({
	// 		status,
	// 		message: err instanceof Error ? err.message : err,
	// 		...other[0]
	// 	})
	// }
	res.cc = (status, message, ...other) => {
		const response = new Response(status, message)
		// res.send(Object.assign(response, other[0]))
		console.log(Object.assign({},response, other[0]));
		// res.status(status).json(Object.assign({},response, other[0]))
		res.status(status).json({...response, ...other[0]})
	}
	next()
})

//将导入的路由中间件使用
app.use(userRouter)


app.use((err, req, res, next) => {
	console.log("message", err.message);
	if(err.name === 'UnauthorizedError'){
		return res.cc(401)
	}
	else if(err instanceof joi.ValidationError){
		console.log('表单校验失败');
		return res.cc(400, err)
	}
	return res.cc(500, err)
})


app.listen(serverConfig.httpPort, () => {
	console.log(`服务已启动: http://127.0.0.1:${serverConfig.httpPort}`)
})